import React from "react";

import { addon, Ref, getObject, log } from "pao-aop";

import { reactControl, ReactViewControl, ReactView, ReactViewState } from "pao-aop-client";
import FormCreator, { InputType } from "src/business/components/form-creator";
import { IExternalLinkSignService, ExternalLinksSign } from "src/models/externalLinksSign";
import { match } from "react-router";
import { message, Button, Select } from "antd";
import { NTModal } from "src/projects/industryInternetSign/components/modal";
import { SIGN_ID, ROUTE_PATH } from "../../app/util-tool";
import { IndustryInternetSignAppStorage } from "../../app/appStorage";
import { User } from "src/business/models/user";
import { GetFieldDecoratorOptions, FormProps } from "antd/lib/form/Form";
import { ICompanyTemplateSignService } from "src/models/companySign";
import NTDivStyle from "src/business/style-components/div-style";
const Option = Select.Option;

/**
 * 组件：外链标识编辑状态
 */
export interface ChangeExternalLinkViewState extends ReactViewState {
    info: ExternalLinksSign;
    /** modal显示判断 */
    visible: boolean;
    /** 二维码显示判断 */
    showCode: boolean;
    /** 地址 */
    src?: string;
    /** 用户信息 */
    user_data?: User;
    /** 标识输入框是否可编辑 */
    check_code: boolean;
    /** 链接前缀 */
    before: string;
    /** 标识码显示前缀 */
    before_handle_code?: string;
    /** 滚动条 */
    loading?: boolean;
}

/**
 * 组件：外链标识编辑
 */
export class ChangeExternalLinkView extends ReactView<ChangeExternalLinkViewControl, ChangeExternalLinkViewState> {
    constructor(props: ChangeExternalLinkViewControl) {
        super(props);
        this.state = {
            info: {},
            visible: false,
            showCode: false,
            src: '',
            check_code: false,
            before: 'http://',
            before_handle_code: '',
            loading: false
        };
    }

    componentWillMount() {

    }
    componentDidMount() {
        this.setState({
            loading: true
        });
        let { [SIGN_ID]: id } = this.props.match!.params;
        let user_data = IndustryInternetSignAppStorage.getCurrentUser();
        if (id) {
            this.externalLinkService!()!.get_external_link!(id)!
                .then((info) => {
                    if (info && info['link_website']) {
                        let before = info['link_website'].slice(0, info['link_website']!.indexOf('://') + 3);
                        this.setState({
                            before
                        });
                    }
                    this.setState({
                        info: info,
                        user_data: user_data[0], // 以后梦晴改成对象后，把0去掉
                        check_code: true,
                        before_handle_code: info ? info!.handle_code!.slice(0, info!.handle_code!.indexOf('@') + 1) : this.state.before_handle_code,
                        loading: false
                    });
                })
                .catch(error => {
                    console.log(error);
                    this.setState({
                        loading: false
                    });
                });
        } else {
            this.setState({
                user_data: user_data[0], // 以后梦晴改成对象后，把0去掉
                before_handle_code: (user_data[0] ? user_data[0].account : "") + '/tzbs@',
                check_code: false,
                loading: false
            });
        }
    }

    /**
     * 上传base64，返回url地址
     * 保存数据
     */
    async upload_base64(code: string, base64: string, data: ExternalLinksSign) {
        let new_code = code.replace('/', '-');
        const src = await this.companyTemplateSignService!()!.upload_rc_code!(new_code, base64)!;
        data.rc_code = '/' + src.url;
        data['link_website'] = this.state.before + data['link_website'];
        this.setState({ src: '/' + src.url });
        await this.externalLinkService!()!.insert!(data)!;
    }
    /**
     * 生成二维码图片，返回url地址
     * 保存数据
     */
    async generateIdentifierQRCode(code: string, data: ExternalLinksSign) {
        const src = await this.companyTemplateSignService!()!.get_qr_code!(code)!;
        data.rc_code = '/' + src.url;
        data['link_website'] = this.state.before + data['link_website'];
        this.setState({ src: '/' + src.url });
        let result = await this.externalLinkService!()!.insert!(data)!;
        if (result) {
            this.setState({
                showCode: true
            });
            message.info('保存成功');
        } else {
            message.info('保存失败');
        }
    }

    /**
     * 生成二维码base64
     */
    createCode(data: ExternalLinksSign, code: string) {
        // let thiz = this;
        // build_qrCode(code, function (val: any) {
        //     thiz.upload_base64(code, val, data)
        //         .then((result) => {
        //             message.info("保存成功");
        //             thiz.setState({
        //                 showCode: true,
        //                 loading: false
        //             });
        //         })
        //         .catch(error => {
        // thiz.setState({
        //     loading: false
        // });
        //             message.info('保存失败：' + error.message);
        //         });
        // });
        this.setState({
            loading: true
        });
        this.generateIdentifierQRCode(data!.handle_code!, data)
            .then(() => {
                this.setState({
                    loading: false
                });
                message.info("保存成功");
            })
            .catch(error => {
                this.setState({
                    loading: false
                });
                message.info('保存失败：' + error.message);
                log("generateIdentifierQRCode", error.message);
            });
    }

    /** 提交 */
    createExternalLink = (err: any, data: ExternalLinksSign) => {
        this.setState({ visible: true, loading: true });
        let { [SIGN_ID]: id } = this.props.match!.params;
        if (id) {
            data.id = id;
            data.company_handle_name = this.state.info.company_handle_name;
            data.company_handle_code = this.state.info.company_handle_code;
        } else {
            let company_sign = IndustryInternetSignAppStorage.getCurrentCompanySign();
            if (company_sign) {
                data.company_handle_name = company_sign.handle_name;
                data.company_handle_code = company_sign.handle_code;
            }
        }
        data.handle_code = (this.state.before_handle_code ? this.state.before_handle_code : "") + data!.handle_code;
        this.createCode(data, data.handle_code);
        // data.rc_code = this.state.src;   
    }

    externalLinkService?() {
        return getObject(this.props.externalLinkService_Fac!);
    }

    /**
     * 初始化企业服务
     */
    companyTemplateSignService?() {
        return getObject(this.props.companyTemplateSignService_fac!);
    }

    onRowSelection = (contents: string[]) => {
        console.log('selectedRow changed: ', contents);
    }
    onChangeLink = (e: any) => {
        console.log(e);
        debugger;
        this.setState({
            before: e
        });
    }
    render() {
        let selectBefore;
        let { info, before_handle_code } = this.state;
        if (info && info['link_website']) {
            info['link_website'] = info['link_website'].slice(info['link_website']!.indexOf('://') < 0 ? 0 : info['link_website']!.indexOf('://') + 3);
        }
        selectBefore = (
            <Select key={Math.random().toString()} defaultValue={this.state.before} style={{ width: 90 }} onChange={this.onChangeLink}>
                <Option value="http://">http://</Option>
                <Option value="https://">https://</Option>
            </Select>
        );
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
        };

        let edit_props = {
            loading: this.state.loading,
            form_items_props: [
                {
                    title: "跳转标识信息",
                    need_card: true,
                    input_props: [
                        {
                            type: InputType.input,
                            label: "跳转标识名称",
                            decorator_id: "handle_name",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入跳转标识名称" }],
                                initialValue: info["handle_name"],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入跳转标识名称"
                            }
                        },
                        {
                            type: InputType.input,
                            label: "跳转标识",
                            decorator_id: "handle_code",
                            field_decorator_option: {
                                // rules: [{ validator: checkCode }],
                                rules: [{ required: true, message: "请输入跳转标识" }],
                                initialValue: info && info!.handle_code ? info!.handle_code!.slice(info!.handle_code!.indexOf('@') + 1) : '',
                            } as GetFieldDecoratorOptions,
                            option: {
                                addonBefore: before_handle_code ? before_handle_code : "",
                                placeholder: "请输入跳转标识",
                                disabled: this.state.check_code
                            }
                        },
                        {
                            type: InputType.input,
                            label: "跳转网址",
                            decorator_id: "link_website",
                            field_decorator_option: {
                                rules: [{ required: true, message: "请输入跳转网址" }],
                                initialValue: info["link_website"],
                            } as GetFieldDecoratorOptions,
                            option: {
                                placeholder: "请输入跳转网址",
                                addonBefore: selectBefore
                            }
                        },
                    ]
                }
            ],
            form_item_layout: formItemLayout,
            form_props: {
                hideRequiredMark: true
            } as FormProps,
            row_btn_props: {
                style: {
                    justifyContent: " center"
                }
            },
            other_btn_propps: [
                {
                    text: "返回",
                    cb: () => {
                        console.log("返回回调");
                        this.props.history!.push(ROUTE_PATH.externalLinks);
                    }
                }
            ],
            submit_btn_propps: {
                text: "提交并生成二维码",
                cb: this.createExternalLink
            }
        };
        return (
            <NTDivStyle.NTDefaultDiv>
                <FormCreator {...edit_props} />
                <NTModal
                    visible={this.state.visible}
                    closable={false}
                    title="预览"
                    onCancel={() => { this.setState({ visible: false, showCode: false }); }}
                    onOk={() => { this.setState({ showCode: true, }); }}
                    content={<div style={{ display: 'flex', width: '100%', height: '100%', minHeight: 400, justifyContent: 'center', alignItems: 'center' }}><img src={this.state.src} /></div>}
                    footer={[
                        <Button
                            key="back"
                            onClick={() => {
                                this.setState(
                                    {
                                        visible: false,
                                        showCode: false
                                    },
                                    () => { this.props.history!.push(ROUTE_PATH.externalLinks); });
                            }
                            }
                        >
                            返回
                        </Button>,
                    ]
                    }
                />
            </NTDivStyle.NTDefaultDiv>
        );
    }
}

/**
 * 控件：外链标识编辑控制器
 * @description 控制外链标识编辑
 * @author cxl
 */
@addon('ChangeExternalLinkView', '外链标识编辑', '控制外链标识编辑')
@reactControl(ChangeExternalLinkView, true)
export class ChangeExternalLinkViewControl extends ReactViewControl {
    /**
     * 解析统计服务
     */
    public externalLinkService_Fac?: Ref<IExternalLinkSignService>;

    /**
     * 企业服务
     */
    public companyTemplateSignService_fac?: Ref<ICompanyTemplateSignService>;
    match?: match<{ [SIGN_ID]: string }>;
}